<template>
  <div class="change-trading-dialog-view">

    <el-dialog
      v-model="dialogVisible"
      title="变更交易精细招商信息"
      width="1100px"
      :before-close="handleClose"
    >
      <item-title title="选择变更后使用的招商要素" />

      <el-form label-width="110px">
        <el-form-item label="产品信息">
          <!--                    <div style="display: flex;width: 800px">-->
          <!--                        <product-popover :searchs="productPopularName" @confirm="productConfirm">-->
          <!--                            <el-input v-model="productPopularName" placeholder="请输入产品名称" @blur="onBlur" style="width: 500px"/>-->

          <!--                        </product-popover>-->

          <!--&lt;!&ndash;                        <span style="padding-left: 20px">仅可添加同一产品下的交易终端</span>&ndash;&gt;-->
          <!--                    </div>-->

          <!--                    <el-select v-model="formData.productId" style="width: 100%" @change="productChange" placeholder="请选择交易产品">-->
          <!--                        <el-option v-for="item in productList" :key="item.id" :label="item.name" :value="item.id"/>-->
          <!--                    </el-select>-->

          <san>{{ getProductName(datas) }}</san>

        </el-form-item>

      </el-form>

      <el-form
        ref="refForm"
        class="info-form"
        :inline="true"
        :model="formData"
        :rules="rules"
        label-width="110px"
      >
        <el-row>

          <el-col :span="12">
            <el-form-item
              label="营销模式"
              prop="sellMode"
            >
              <el-select
                v-model="formData.sellMode"
                style="width: 100%"
                placeholder="请选择营销模式"
                @change="modeChange"
              >
                <el-option
                  v-for="item in salesModel.filter((p) => p.value !== 'direct')"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col
            v-if="formData.sellMode !== 'direct'"
            :span="12"
          >
            <el-form-item
              label="代理商名称"
              prop="agentName"
            >
              <el-autocomplete
                v-model="formData.agentName"
                style="width: 100%"
                placeholder="请输入代理商名称"
                :fetch-suggestions="querySearchAsyncAgent"
                @select="handleSelectAgent"
              >
                <template #default="{ item }">
                  <div
                    class="distributeName"
                    v-if="formData.sellMode == 'agent'"
                  >{{ item.agentName }}</div>
                  <div
                    class="distributeName"
                    v-else
                  >{{ item.userName }}</div>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="交易价"
              prop="tradePrice"
            >

              <template v-if="formData.sellMode === 'direct'">
                <price-input
                  v-model:data="formData.tradePrice"
                  placeholder="请输入交易价"
                  is-unit
                  :unit-str="'元/' + unit"
                />
              </template>
              <template v-else>
                <app-trading-popover
                  ref="agentPop"
                  :props-agent="formData"
                  @confirm="agentConfirm"
                >
                  <el-select
                    v-model="formData.tradePrice"
                    placeholder="请选择交易价"
                    style="width: 100%"
                    @focus="agentFocus"
                    @clear="agentClear"
                  >
                    <template #empty />
                  </el-select>
                </app-trading-popover>
              </template>

            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="负责营销职员"
              prop="headId"
            >
              <el-select
                v-model="formData.headId"
                style="width: 100%"
                placeholder="请选择营销职员"
                @change="handlChangeHead"
              >
                <el-option
                  v-for="item in headList"
                  :key="item.id"
                  :label="item.realName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item
              label="最低销量"
              prop="minSale"
            >
              <el-input
                v-model.number="formData.minSale"
                clearable
                placeholder="请输入最低销量"
              >
                <template #append>
                  <span
                    v-if="unit"
                    style="margin-right: 10px"
                  >{{ unit }}/</span>
                  <el-select
                    v-model="formData.minSaleUnit"
                    style="width: 80px;"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in nuitData"
                      :key="item.id"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="销量保证金"
              prop="sellEarnestMoney"
            >
              <el-input
                v-model="formData.sellEarnestMoney"
                clearable
                placeholder="请输入销量保证金"
              />
            </el-form-item>
          </el-col>

        </el-row>

      </el-form>

      <item-title title="选择此代理商下的交易终端" />

      <div style="margin-bottom: 10px">

        <el-button
          type="primary"
          @click="addTerminalClick"
        >添加终端</el-button>

        <el-button
          type="primary"
          @click="allRemove"
        >全部移除</el-button>

      </div>

      <el-table
        style="margin-bottom: 10px"
        max-height="250"
        border
        :data="tableData"
      >
        <el-table-column
          header-align="center"
          align="center"
          label="终端编号"
          prop="terminalNo"
          width="100"
          show-overflow-tooltip
        />
        <el-table-column
          header-align="center"
          align="left"
          label="终端名称"
          prop="terminalName"
          show-overflow-tooltip
        />
        <el-table-column
          header-align="center"
          align="center"
          label="所在地区"
          width="100"
          show-overflow-tooltip
        >
          <template #default="{row}">
            <span>{{ row.provinceName }}/{{ row.cityName }}/{{ row.areaName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="left"
          label="产品信息"
          prop="productInfoDetail.productPopularName"
          width="150"
          show-overflow-tooltip
        />
        <el-table-column
          header-align="center"
          align="center"
          label="终端价(元)"
          width="100"
        >
          <template #default="scope">
            {{ scope.row.terminalPrice }}
          </template>
        </el-table-column>

        <el-table-column
          header-align="center"
          align="center"
          label="当前交易价(元)"
          width="100"
        >
          <template #default="scope">
            {{ scope.row.tradePrice }}
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="当前招商要素编号"
          width="100"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span v-if="scope.row.productPriceStrategyDetail">{{ scope.row.productPriceStrategyDetail.priceNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="操作"
          width="100"
        >
          <template #default="scope">
            <el-button
              type="text"
              @click.stop="onRemoved(scope)"
            >移除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button
            type="primary"
            @click="dialogConfirm"
          >提交审核</el-button>
        </div>
      </template>

    </el-dialog>

    <add-terminal-dialog
      ref="addTerminal"
      :datas="formData"
      :area="areas"
      @confirm="onConfirm"
    />

  </div>
</template>

<script>
import {getScreenAreaData} from '@/utils/areaFuc'
import area from '@/utils/area.js'
import {crmStore} from '@CRM/store'
import {defineComponent, defineAsyncComponent, getCurrentInstance, inject, onMounted, reactive, ref, toRefs,} from 'vue'

export default defineComponent({
  name: 'ChangeTradingDialog',
  components: {
    addTerminalDialog :defineAsyncComponent(
            ()=>import('./addTerminalDialog.vue')
    )
  },
  props: {
    agent: {
      type: Object,
      default: {},
    },
    datas: {
      type: Object,
      default: {},
    },
  },
  setup(props, { emit }) {
    const api = inject('api')
    const currentInstance = getCurrentInstance()
    const salesModel = crmStore.getters['dictionary/getDictionary']['agentType']
    const nuitData =
      crmStore.getters['dictionary/getDictionary']['sell_num_unit']
    const rules = ref({
      agentName: [
        { required: true, message: '请选择代理商名称', trigger: 'blur' },
      ],
      tradePrice: [
        { required: true, message: '请输入交易价', trigger: 'blur' },
      ],
      headId: [
        { required: true, message: '请选择代负责人', trigger: 'change' },
      ],
    })

    var data = reactive({
      dialogVisible: false,
      formData: {
        sellMode: '',
        agentName: '',
        agentId: 0,
        tradePrice: '',
        agentProductId: 0,
        headName: '',
        headId: null,
        minSale: 0,
        minSaleUnit: '1',
        sellEarnestMoney: 0,
        productId: '',
        productPopularName: '',
        terminalType: '',
        region: [],
        oldAgentId:0,
      },
      productPopularName: '',
      productId: '',
      tableData: [],
      selectProduct: {},
      addTerminal: null,
      agentPop: null,
      refForm: null,
      headList: crmStore.getters['company/getHeadOptions'],
      productList: [],
      areas: [],
      unit: '',
    })

    const modeChange = () => {
      data.formData.tradePrice = 0
      data.formData.terminalType = ''
      data.formData.agentProductId = 0
      data.formData.agentId = 0
      data.formData.agentName = ''
      data.formData.region = []
      data.tableData = []
      if (data.formData.sellMode == 'direct') {
        data.areas = area
      } else {
        data.areas = []
      }
    }

    const productConfirm = (val) => {
      if (data.tableData.length) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请先移除全部终端',
        })
        return
      }

      console.log(val)
      data.selectProduct = val
      data.formData.productId = val.id
      data.productPopularName = val.approvalNumber ? val.approvalNumber + '-' : "" +
        val.productPopularName + '-' + val.packSpecs
    }

    const productChange = (val) => {
      if (val) {
        const index = data.productList.findIndex((a) => a.id == val)
        if (index != -1) {
          data.selectProduct = data.productList[index]
          data.formData.productPopularName =
            data.selectProduct.productPopularName
          data.unit = currentInstance.proxy.getLabel(
            'sell_unit',
            data.selectProduct.sellUnit
          )
        }
      } else {
        data.selectProduct = null
        data.unit = ''
      }

      data.formData.agentProductId = ''
      data.formData.tradePrice = ''
      data.formData.region = []
      data.formData.terminalType = ''
      data.areas = []
      data.formData.minSale = 0
      data.formData.minSaleUnit = '1'
      data.formData.sellEarnestMoney = 0
      data.tableData = []
    }

    const onBlur = () => {
      if (data.selectProduct.id) {
        data.productPopularName = data.selectProduct.approvalNumber ? data.selectProduct.approvalNumber + '-' : '' +
          data.selectProduct.productPopularName +
          '-' +
          data.selectProduct.packSpecs
      }
    }

    const onConfirm = (list) => {
      const a = []
      let str = ''
      for (let i = 0; i < list.length; i++) {
        const index = data.tableData.findIndex((a) => a.id == list[i].id)
        if (index == -1) {
          a.push(list[i])
        } else {
          if (str) {
            str = str + ','
          }
          str = str + list[i].terminalName
        }
      }

      if (str) {
        currentInstance.proxy.customMessage({
          type: 'warning',
          message: str + '已添加',
        })
      }

      data.tableData = data.tableData.concat(a)
    }

    const allRemove = () => {
      data.tableData = []
    }

    const onRemoved = (scope) => {
      data.tableData.splice(scope.$index, 1)
    }

    // 获取代理商列表
    const querySearchAsyncAgent = async(queryString, cb) => {
      const a = {
        agentType: data.formData.sellMode,
        keyWord: queryString,
      }
      let results = []
      const res = await api.editorial.EDITORIAL_KEYWORDS(a)
      if (!res.code && res.data) {
        results = res.data.list || []
      }
      cb(results)
    }

    // 代理商事件
    const handleSelectAgent = (val) => {
      data.formData.agentId = val.id
      if (data.formData.sellMode == 'agent') {
        data.formData.agentName = val.agentName
      } else {
        data.formData.agentName = val.userName
      }

      data.formData.agentProductId = 0
      data.formData.tradePrice = ''
    }

    // 交易价
    const agentConfirm = (val) => {
      console.log(val)
      data.formData.agentProductId = val.id
      data.formData.tradePrice = val.tradePrice
      data.formData.region = val.region
      data.formData.terminalType = val.terminalType
      data.formData.minSale = val.minSale
      data.formData.minSaleUnit = val.minSaleUnit
      data.formData.sellEarnestMoney = val.minSalePromise
      data.areas = getScreenAreaData(data.formData.region)
    }

    // 打开交易价弹框
    const agentFocus = (val) => {
      if (val) {
        data.agentPop.openPopover()
      }
    }

    // 取消交易价弹框
    const agentClear = () => {
      data.formData.agentProductId = 0
      data.formData.tradePrice = ''
    }

    const handleClose = () => {
      data.formData.region = []
      data.formData.productId = ''
      data.refForm.resetFields()
      setTimeout(() => {
        data.tableData = []
        data.dialogVisible = false
        data.refForm.clearValidate()
      }, 100)
    }

    const dialogConfirm = () => {
      if (!data.tableData.length) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请选择终端',
        })
        return
      }
      if (data.formData.tradePrice) {
        for (let i = 0; i < data.tableData.length; i++) {
          const item = data.tableData[i]
          if (data.formData.tradePrice > item.terminalPrice) {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: '交易价不能大于终端价',
            })
            return
          }
        }
      }

      data.refForm.validate((val) => {
        if (val) {
          const a = { ...data.formData }
          a.sellEarnestMoney = Number(a.sellEarnestMoney)
          a.ids = []
          data.tableData.forEach((item) => {
            a.ids.push(item.id)
          })

          api.signedAgent
            .RELATIONSTANDARD_SET_NEW_AGENT_PRICE(a)
            .then((res) => {
              if (!res.code) {
                currentInstance.proxy.customMessage({
                  type: 'success',
                  message: '提交成功',
                })

                emit('success')

                handleClose()
              }
            })
        }
      })
    }

    const openDialog = () => {
      data.selectProduct = props.datas
      data.formData.oldAgentId = props.agent.id
      data.formData.productId = props.datas.productId
      data.formData.productPopularName = props.datas.productPopularName
      data.unit = currentInstance.proxy.getLabel(
        'sell_unit',
        props.datas.sellUnit
      )
      data.dialogVisible = true
    }

    const addTerminalClick = () => {
      if (!data.formData.productId) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: '请选择产品',
        })
        return
      }

      if (data.formData.sellMode != 'direct') {
        console.log(data.formData)
        if (!data.formData.agentId) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '请选择代理商',
          })
          return
        }
        if (!data.formData.agentProductId) {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: '请选择交易价',
          })
          return
        }
      }

      data.addTerminal.openDialog()
    }

    // 负责人事件
    const handlChangeHead = (val) => {
      const index = data.headList.findIndex((a) => a.id === val)
      if (index !== -1) {
        data.formData.headName = data.headList[index].realName
      }
    }

    onMounted((_) => {
      if (props.agent.agentType) {
        data.formData.sellMode = props.agent.agentType
      }
      if (props.agent.id) {
        data.formData.agentId = props.agent.id
        data.formData.agentName = props.agent.agentName
      }

      api.signedAgent.AGENTPRODUCT_PRODUCT_LIST(props.agent.id).then((res) => {
        if (!res.code && res.data) {
          res.data.agentProduct.forEach((item) => {
            if (item.productName) {
              item.name = item.approvalNumber +
                      '-' +
                      item.productPopularName +
                      '-' +
                      item.packSpecs
            }

          })

          data.productList = res.data.agentProduct
        }
      })
    })

    return {
      ...toRefs(data),
      salesModel,
      nuitData,
      rules,

      handleClose,
      dialogConfirm,
      openDialog,
      productConfirm,
      onBlur,
      addTerminalClick,
      onConfirm,
      allRemove,
      querySearchAsyncAgent,
      handleSelectAgent,
      agentConfirm,
      agentFocus,
      agentClear,
      handlChangeHead,
      modeChange,
      onRemoved,
      productChange,
    }
  },
})
</script>

<style lang="scss" scoped>
.change-trading-dialog-view {
  .info-form {
    .el-form-item {
      width: 100%;
    }
  }
}
</style>
